import asyncio
import time

###############################################简单示例######################################################

async def job(t):                # job要花t时间完成
    await asyncio.sleep(t)       # 睡眠的时候还能干别的

async def main(loop):
    await asyncio.wait([loop.create_task(job(t))for t in range(3)])

begin = time.time()
loop = asyncio.get_event_loop()  # 获得事件循环
loop.run_until_complete(main(loop))
end = time.time()
print(end-begin)

###############################################加速爬虫######################################################
import aiohttp
async def task(session):
    response = await session.get(url)                              # 在主要费时的函数前加await,在运行时不等待函数结束直接运行下面的代码
    return str(response.url)
async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(task(session))for _ in range(2)] # 主要的循环任务
        done, pending = await asyncio.wait(tasks)            # await asyncio.wait表示等待所有工作做完再返回最后结果
        all_results = [r.result() for r in done]
        print(all_results)

url = 'https://www.bilibili.com/video/BV1MW411B7rv?p=11'
begintic = time.time()
asyncio.run(main())
endtoc = time.time()
print(endtoc-begintic)